package cn.bopomo.dealer.wow.action;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.jfree.data.general.DefaultPieDataset;
import org.json.JSONObject;

import cn.bopomo.dealer.base.action.BaseAction;
import cn.bopomo.dealer.base.util.Page;
import cn.bopomo.dealer.wow.service.IYouyiService;
import cn.bopomo.dealer.wow.service.impl.YouyiServiceImpl;
import cn.bopomo.dealer.wow.vo.Wow711CardObject;

import com.metaparadigm.jsonrpc.JSONSerializer;

public class CheckWowCardAction extends BaseAction {

	public static final String REGEX_INT = "^[1-9]*[0-9]*$";
	/*public static final String REGEX_DATE = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\-\\s]?((((0?" +
      "[13578])|(1[02]))[\\-\\-\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))" +
      "|(((0?[469])|(11))[\\-\\-\\s]?((0?[1-9])|([1-2][0-9])|(30)))|" +
      "(0?2[\\-\\-\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][12" +
      "35679])|([13579][01345789]))[\\-\\-\\s]?((((0?[13578])|(1[02]))" +
      "[\\-\\-\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))" +
      "[\\/\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\-\\s]?((0?[" +
      "1-9])|(1[0-9])|(2[0-8]))))))$";*/
	//(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$";
      public static final String REGEX_DATE = "^((((1[6-9]|[2-9]\\d)\\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\\d|3[01]))|(((1[6-9]|[2-9]\\d)\\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\\d|30))|(((1[6-9]|[2-9]\\d)\\d{2})-0?2-(0?[1-9]|1\\d|2[0-8]))|(((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29))$";
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Cache-control","no-cache");
		
		//判断有无权限
		if (!this.hasPermission(request)){
			//error
			response.getWriter().write("errors:你没有权限进行该操作");
			return null;
		}
		
		String cardNo = request.getParameter("cardNo");
		
		IYouyiService ys = new YouyiServiceImpl();
		
		//第一种查询方式---卡号查找使用情况
		if (!"".equals(cardNo) && cardNo != null){
			
			if (cardNo.length() != 15 || !this.isValidateData(this.REGEX_INT,cardNo)){
				//跳出报错
				response.getWriter().write("errors:您输入的卡号格式不正确");
				return null;
			}
			
			Wow711CardObject cardObj = ys.getCardUsedInfo(cardNo);
			
			JSONSerializer jsonSerializer = new JSONSerializer();
			try {
				jsonSerializer.registerDefaultSerializers();
				response.getWriter().write(jsonSerializer.toJSON(cardObj));
				
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				response.getWriter().write("errors:服务器出错，请稍后再试");
				return null;
			}
			
			return null;
		}
		//第二种查询方法
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		String value = request.getParameter("cardValue");
		String useFor = request.getParameter("useFor");
		String pageSize = request.getParameter("pageSize");
		String photo = request.getParameter("photo");
		boolean is_newRequest = false;
		if ("true".equals(photo))
			is_newRequest = true;
		Wow711CardObject conditionObj = null;
		
		if ((value != null && !"".equals(value)) || useFor != null){
			conditionObj = new Wow711CardObject();
			conditionObj.setUseFor(useFor);
			if (value != null && !"".equals(value)){
				BigDecimal tmp_value = new BigDecimal(value + ".00");
				conditionObj.setCardValue(tmp_value.toString());
			}else
				conditionObj.setCardValue(null);
		}
		
		
		if (startDate != null && this.isValidateData(REGEX_DATE,startDate) && endDate != null && this.isValidateData(REGEX_DATE,endDate)){
			
			List cardList = ys.getCardUsedInfos(startDate,endDate,conditionObj);
			DefaultPieDataset dataset = null;
			
			if (is_newRequest){
				dataset = ys.getPieChartDataSet(cardList);
			}
			//String fileName = ChartUtil.generatePieChart(dataset,"test",200,150,request.getSession(),new PrintWriter(response.getOutputStream()));
			//System.out.println("fileName:" + fileName);
			if (cardList == null){
				response.getWriter().write("errors:您的日期格式可能有误，或该时间段没有数据");
				return null;
			}
			
			if ("".equals(pageSize) || pageSize == null)
				pageSize = "1";
			
			
			Page resultPage = new Page(cardList);
			List resultList = ys.toPageList(cardList,Integer.parseInt(pageSize),resultPage);
			resultPage.setList(resultList);
			resultPage.setTarget(request.getRequestURI());
			resultPage.setAJAX(true);
			Map parameterMap = new HashMap();
			
			parameterMap.put("startDate",startDate);
			parameterMap.put("endDate",endDate);
			if(value != null && !"".equals(value)){
				parameterMap.put("cardValue",value);
			}
			
			if(useFor != null && !"".equals(useFor)){
				parameterMap.put("useFor",useFor);
			}
			
			resultPage.setParameterMap(parameterMap);
			resultPage.setCurPage(Integer.parseInt(pageSize));
			JSONSerializer jsonSerializer = new JSONSerializer();
			try {
				jsonSerializer.registerDefaultSerializers();
				JSONObject json = new JSONObject();
				json.put("cardList",jsonSerializer.toJSON(resultList));
				json.put("pageStr", resultPage.getPageStr());
				if (is_newRequest){
					request.getSession().setAttribute("wow_cardDateSet",dataset);
					json.put("chartDataset","wow_cardDateSet||" + startDate + "---" + endDate );
				}
				response.getWriter().write(json.toString());
				return null;
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				response.getWriter().write("errors:服务器出错，请稍后再试");
				return null;
			}
			
		}else{
			response.getWriter().write("errors:您的日期格式可能有误");
			return null;
		}
		
		
		
	}
	
	protected boolean isValidateData(String regEx, String str){
		Pattern pattern= Pattern.compile(regEx);
		Matcher m=pattern.matcher(str); 
		
		return m.find();
	}
	
	public static void  main(String[] sa){
		CheckWowCardAction ca = new CheckWowCardAction();
		System.out.println(ca.isValidateData(ca.REGEX_DATE,"2007-02-29"));
	}
}
